import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/video/view/video_detail_bottom_menu.dart';
import 'package:xvideos/hj_page/video/view/video_detail_info_widget.dart';
import 'package:xvideos/hj_utils/api_service/common_service.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/banner/ads_grid_view_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:video_player/video_player.dart';

import '../../../hj_utils/global.dart';
import '../../../routers/jump_router.dart';
import '../../../tools_base/debug_log.dart';
import '../../../tools_base/refresh/pull_refresh.dart';
import '../../home_business/home_cell_style/video_simple_cell_widget.dart';

/// 视屏播放页数据详情
class VideoDetailView extends StatefulWidget {
  final VideoModel? model;
  final VideoPlayerController? controller;
  final Function? callback;
  final Function(VideoModel model)? vmCallback;
  final Function(int isCodeless)? unCodeCallback; // 1:源视频,2:中文字幕,3:破解版

  const VideoDetailView({
    super.key,
    this.model,
    this.controller,
    this.callback,
    this.vmCallback,
    this.unCodeCallback,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailViewState();
  }
}

class _VideoDetailViewState extends State<VideoDetailView> with AutomaticKeepAliveClientMixin {
  RefreshController? refreshController;

  VideoPlayerController? get vpController => widget.controller;

  VideoModel? get videoModel => widget.model;

  List<VideoModel>? moreVideoArr;
  int currentPage = 1;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      _loadData();
    });
  }

  Future<bool> safeFlashUI() async {
    if (!mounted) return false;
    if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.idle) {
      await SchedulerBinding.instance.endOfFrame;
      if (!mounted) return false;
    }
    setState(() {});
    return true;
  }

  bool isLoading = false;

  void _loadData({int page = 1, int size = 10}) async {
    try {
      if (isLoading) return;
      isLoading = true;
      setState(() {});
      final retTemp = await CommonService.getRecommendList(
        pageNumber: page,
        pageSize: size,
        vid: videoModel?.id,
      );
      currentPage = page;
      moreVideoArr ??= [];
      if (currentPage == 1) {
        moreVideoArr?.clear();
      }
      moreVideoArr?.addAll((retTemp?.videos ?? <VideoModel>[]));
      if (retTemp?.hasNext == true) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
    } catch (e) {
      refreshController?.loadComplete();
      debugLog(e);
    }
    moreVideoArr ??= [];
    isLoading = false;
    safeFlashUI();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return pullYsRefresh(
      // refreshController: refreshController,
      onInit: (ctr) => refreshController = ctr,
      enablePullDown: false,
      enablePullUp: true,
      onLoading: (refreshController) => _loadData(page: currentPage + 1),
      child: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(left: 12, right: 12),
              child: VideoDetailInfoWidget(
                model: videoModel,
                controller: widget.controller,
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(12, 18, 12, 0),
              child: VideoDetailBottomMenu(model: videoModel),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(12, 18, 12, 18),
              child: 0.5.line,
            ),
          ),
          // /// 视频播放页广告
          SliverToBoxAdapter(
            child: AdsGridViewWidget(
              6,
              padding: EdgeInsets.only(left: 12, bottom: 18),
              horCount: 5.3,
            ),
          ),

          if (moreVideoArr?.isNotEmpty == true) ...[
            SliverToBoxAdapter(
              child: Container(
                padding: const EdgeInsets.only(bottom: 12),
                margin: const EdgeInsets.only(left: 12),
                child: Text(
                  "猜你喜欢",
                  style: TextStyle(
                    color: Color(0xE5FFFFFF),
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
            SliverPadding(
              padding: EdgeInsets.only(left: 12, right: 12),
              sliver: SliverGrid.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 168 / 154,
                  mainAxisSpacing: 12,
                  crossAxisSpacing: 6,
                ),
                itemCount: moreVideoArr?.length ?? 0,
                itemBuilder: (context, index) {
                  VideoModel acModel = moreVideoArr![index];
                  return VideoSimpleCellWidget(
                    videoModel: acModel,
                    onTap: () {
                      if (acModel.sourceURL?.isNotEmpty == true) {
                        if (acModel.id != videoModel?.id) {
                          if ((acModel.playTime ?? 300) < 300) {
                            widget.controller?.pause();
                            pushToVideoPage(videoModel: acModel);
                          } else {
                            widget.vmCallback?.call(acModel);
                          }
                          // pushToReplace(context, VideoPage(model: acModel));
                        } else {
                          showToast("当前视频正在播放");
                        }
                      } else {
                        widget.controller?.pause();
                        pushToVideoPage(videoModel: acModel);
                      }
                    },
                  );
                },
              ),
            ),
          ],
        ],
      ),
    );
  }
}
